<template>
  <div>
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      v-loading="loading"
      @select="select"
      @select-all="selectAll"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        align="center"
        :selectable="selectable"
        width="55">
        <!-- <template slot-scope="scope">
          <el-checkbox v-model="scope.row.checked" @change="pageCheckEv(scope)"></el-checkbox>
        </template> -->
      </el-table-column>
      <el-table-column
        prop="commodity.name"
        label="商品名"
        align="center"
        width="120">
      </el-table-column>
      <el-table-column 
        label="图片"
        align="center"
        width="120">
        <template slot-scope="scope">
          <div class="demo-image__preview">
            <el-image 
              style="width: 50px; height: 50px"
              :src="scope.row.commodity.image"
              :preview-src-list="[scope.row.commodity.image]">
            </el-image>
          </div>
        </template>
        <!-- <el-image></el-image> -->
      </el-table-column>
      <el-table-column
        label="单价"
        align="center"
        width="120">
        <template slot-scope="scope">{{ scope.row.commodity.price|formatPrice}}</template>
      </el-table-column>
      <el-table-column
        prop="commodity.brand.name"
        label="商品品牌"
        align="center"
        show-overflow-tooltip>
      </el-table-column>
      <el-table-column
        align="center"
        label="数量">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.number" @change="handleChange($event,scope.row)" size="small" :min="1" :max="scope.row.commodity.stock" label="描述文字"></el-input-number>
        </template>
       <!-- <el-input-number v-model="num" @change="handleChange" size="small" :min="1" :max="10" label="描述文字"></el-input-number> -->
      </el-table-column>
      <el-table-column
        label="总价"
        align="center"
        show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.number*scope.row.commodity.price|formatPrice}}</template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
            <el-popconfirm
              title="这是一段内容确定删除吗？"
              @confirm="handleDelete(scope.row)"
            >
              <el-button slot="reference" size="mini"
            type="danger">删除</el-button>
            </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px;background-color:#f8bf1b;height:60px">
      <el-tag type="success">总价:{{totalPrice}}</el-tag>
      <el-button style="float:right;margin-right:5%" @click="toSumbit()">结算</el-button>
    </div>
    <el-dialog
    title="提示"
    :visible.sync="dialogVisible"
    width="50%">
      <el-descriptions title="订单信息" :border="true" :column="3" size="mini" :contentStyle="rowCenter" :labelStyle="rowCenter">
        <template v-for="(item,id) in multipleSelection">
          <el-descriptions-item :key="id">
            <template slot="label" label="s">
              商品名
            </template>
            {{item.commodity.name}}
          </el-descriptions-item>
          <el-descriptions-item :key="id">
            <template  slot="label">
              图片
            </template>
            <el-image style="width: 50px; height: 50px" :preview-src-list="[item.commodity.image]" :src="item.commodity.image"></el-image>
          </el-descriptions-item>
          <!-- <el-descriptions-item :key="id">
            <template  slot="label">
              数量
            </template>
            {{item.number}}
          </el-descriptions-item> -->
          <el-descriptions-item :key="id">
            <template  slot="label">
              商品总价
            </template>
            {{item.commodity.price*item.number|formatPrice}}
          </el-descriptions-item>
          <el-divider :key="id"></el-divider>          
        </template>
      </el-descriptions>
      <el-descriptions title="个人信息" direction="vertical" :border="true" :column="4" size="small">
        <el-descriptions-item label="手机号">{{user.phone}}</el-descriptions-item>
          <el-descriptions-item label="收货人">
            {{user.nickName}}
            <!-- <el-tag size="small">学校</el-tag> -->
          </el-descriptions-item>
          <el-descriptions-item label="总价">
            {{totalPrice|formatPrice}}
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            <!-- <el-image @click="payIt" :src="'https://td.cdn-go.cn/enterprise_payment/v0.1.2/logo.svg'"></el-image> -->
            <!-- <el-image style="width: 100px; height: 50px" @click="payIt" :src="'https://upload.shejihz.com/2020/02/2b85d1226f0e65a7710f8b9c3535d42c.jpg_auto25xauto'"></el-image> -->
            <el-radio v-model="payType" label="1">支付宝支付</el-radio>
          </el-descriptions-item>
          <el-descriptions-item label="居住地" :contentStyle="{'width':'30%'}">
            <!-- 获取数据库的信息，赋值选取 有空再处理-->
            <el-cascader
            size="large"
            :options="options"
            v-model="selectedOptions"
            @change="handleChangeAddress">
          </el-cascader>
          </el-descriptions-item>
          <el-descriptions-item label="详情地址">
            <!-- 江苏省苏州市吴中区吴中大道 1188 号 -->
            <el-input v-model="addressDetail" placeholder="请输入详情地址"></el-input>
          </el-descriptions-item>

      </el-descriptions>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="payIt">确 定</el-button>
    </span>
  </el-dialog>
    <!-- <el-dialog
      title="提示"
      :visible.sync="dialogVisible2"
      width="30%">
      <span>这是一段信息</span>
    </el-dialog> -->
  </div>
</template>

<script>

import request from "@/utils/request"
import { regionData ,codeToText } from 'element-china-area-data'
import qs from 'qs';

  export default {
    name:"Cart",
    data(){
      return {
        loading:false,
        // checked:true,
        dialogVisible:false,
        // dialogVisible2:false,
        // num:1,
        user:null,
        tableData: [],
        multipleSelection: [],
        filterData:[],
        total:0,
        rowCenter:{
         "text-align":"center" 
        },
        options: regionData ,
        selectedOptions: [],
        addressDetail:"",
        payType:"1",
        address:"",
        ordersItem:[],
        cart:[],
        order:{},
        orderNo:"",
      }
    },
    created(){
        this.user = this.$store.state.user
        if(this.user!=null){
          this.loadUserCartsInfo()
        }
        // console.log('this :>> ', this);

    },
    methods: {
      loadUserCartsInfo(){
        this.loading=true
        request.get("/cart/getCarts",{
          params:{
            id:this.user.id
          }
        }).then(res =>{
          this.tableData = res.data.carts
          //初始化选取
          // this.$nextTick(() => {
            setTimeout(()=>{
            for (let i = 0; i < this.tableData.length; i++) {
              if (this.tableData[i].checked == 1) {
                // console.log('this.tableData[i].checked :>> ', this.tableData);
                this.$refs['multipleTable'].toggleRowSelection(this.tableData[i],true)
              }
            }
            },0)
          // })]
          this.loading=false
        })
      },
      handleSelectionChange(rows) {
        this.multipleSelection = rows;
        console.log('rows--- :>> ', rows)
      }, 
      handleDelete(row) {
         request.delete("/cart/deleteCart",{
           params:{
             id:row.id
           }
         }).then(res=>{
           this.loadUserCartsInfo()
            console.log('delete-result :>> ', res.result);
         })
      },
      toSumbit(){
        this.dialogVisible=true
        this.selectedOptions=""
        this.addressDetail=""
      },
      handleChange(newVal,row){
        const arr = [];
        if(newVal>=row.commodity.stock){
          this.$message({
            type:"warning",
            message:"达到库存上限了"
          })
        }
        if(newVal<=1){
          this.$message({
            type:"warning",
            message:"不能再低了"
          })
        }
        //TODO 变化修改数据库的cart----判断库存和选择的数量
        arr.push(row)
        request.put("/cart/updateCart",arr).then(res =>{
            // this.loadUserCartsInfo()
            console.log('update-result :>> ', res.result);
        })
      },
      selectable(row){
        if(row.commodity.stock<row.number){
          // this.multipleSelection.
          return false
        }else{
          return true
        }
        // console.log('selecetable-row :>> ', row);
      },
      select(selection,row){//单选
      const arr = [];
      console.log('selection---- :>> ', selection);
        if(row.checked==1){
          row.checked=2
          arr.push(row)
          request.put("/cart/updateCart",arr).then(res =>{
            // console.log('res.result1 :>> ', res.result);
          })
        }else{
          row.checked=1
          arr.push(row)
          request.put("/cart/updateCart",arr).then(res =>{
            // console.log('res.result1 :>> ', res.result);
          })
        }
        console.log('row--- :>> ', row);
      },
      selectAll(selections){//全选  T，part-1：
        /**
         * TODO优化连续请求的问题
         * 1. 选中的==初始渲染的值  进行包装list返回后端
         * 2. 选中的＜初始渲染的值 pass不用考虑这个
         * 3. 选中的==0 进行包装list返回后端
         */
        if(selections.length==this.tableData.length){
          //全选,checked全改为1 
          // selections.forEach((selection)=>{
          //   selection.checked=1
          //   request.put("/cart/updateCart",selection).then(res =>{
          //     console.log('res.result1 :>> ', res.result);
          //   })
          // })
          //version - 1
          selections.forEach((selection)=>{
            selection.checked=1
          })
          request.put("/cart/updateCart",selections).then(res =>{
            console.log('res.result1 :>> ', res.result);
          })
        }
        if(selections.length === 0){
          this.tableData.forEach((data)=>{
              data.checked = 2
          })
          request.put("/cart/updateCart",this.tableData).then(res =>{
            console.log('res.result1 :>> ', res.result);
          })
        }
        // if(selections.length<this.tableData.length){
        //   this.filterData = this.tableData.filter(
        //     item=>{
        //       return !selections.find(
        //         prop=>{
        //           return prop.id==item.id
        //         }
        //       )
        //     }
        //   )
        //   this.filterData.forEach((data)=>{
        //     data.checked=2
        //     // setTimeout(()=>{
        //     //     request.put("/cart/updateCart",data).then(res =>{
        //     //     console.log('res.result2 :>> ', res.result);
        //     //   })
        //     // },500)
        //     //连续的请求可能有问题
        //     request.put("/cart/updateCart",data).then(res =>{
        //       console.log('res.result2 :>> ', res.result);
        //     })
        //   })  
        //   //修改状态,不包括的没有的改为2
        // }
      },
      handleChangeAddress (value) {
        this.address = this.getCodeToText(value)+this.addressDetail
        // console.log(value)
      },
      payIt(){
        this.order.address = this.address;
        this.order.state = 1;
        this.order.postage = 0;
        this.order.payment = this.total;
        console.log('order---- :>> ', this.order);
        this.multipleSelection.forEach((selection)=>{
          var value = {};
          value.commodity = selection.commodity
          value.name = selection.commodity.name
          value.price = selection.commodity.price
          value.number = selection.number
          value.totalPrice = selection.number*selection.commodity.price
          value.image = selection.commodity.image//后端处理
          this.ordersItem.push(value)
        })
        console.log('ordersItem :>> ', this.ordersItem)
        this.cart = this.multipleSelection
        console.log('cart :>> ', this.cart);
        /* 调用支付接口 */
        /**
         * 1.调用创建订单接口
         * 2.调用创建订单子项接口
         * 3.删除购物车的商品
         * 4.修改商品库存
         * 5.调用支付宝接口
         * 6.回跳
         */
        let data={}
        data.user = this.user
        data.orders = this.order,
        data.orderItemList = this.ordersItem,
        data.cartList = this.cart,
        console.log('data :>> ', data);
        const randomNumber = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;
        let randomName = this.user.nickName+randomNumber
        request.post("/orders/orderSubmit",data).then((res)=>{
            // console.log('cartsubmit-res :>> ', res);
            this.orderNo = res.data.ordersNumber
            console.log('res.data.ordersNumber :>> ', res.data.ordersNumber);
            console.log('this.orderNo------ :>> ', this.orderNo);
        })
        // console.log('address :>> ', this.getCodeToText(this.selectedOptions)+this.addressDetail);
        //TODO 支付跳转
        // this.dialogVisible2=true
        console.log('orderNo :>> ', this.orderNo);
        console.log('total :>> ', this.total);
        console.log('randomName :>> ', randomName);
        setTimeout(()=>{
          let url = 'http://172.17.33.23:8888/alipay/pay?traceNo=' + this.orderNo + "&totalAmount=" + this.total + '&subject=' + randomName
          window.open(url,'_self');
        },1000)
        // this.dialogVisible=false
      },
      //地址解析
      getCodeToText(codeArray) {
          if(null==codeArray){
            return null;
          }

          let area = "";
          switch (codeArray.length) {
            case 1:
              area += codeToText[codeArray[0]];
              break;
            case 2:
              area += codeToText[codeArray[0]] + codeToText[codeArray[1]];
              break;
            case 3:
              area +=
                codeToText[codeArray[0]] +
                // "/" +
                codeToText[codeArray[1]] +
                // "/" +
                codeToText[codeArray[2]];
              break;
            default:
              break;
          }
          // console.log('area :>> ', area);
          return area;
      }

    },
    computed:{
      totalPrice(){
        let total=0;
        this.multipleSelection.forEach((row)=>{
          total+=row.commodity.price*row.number
        })
        this.total=total
        return total
      }
    },
    filters:{
      formatPrice(val){
        return val+"￥"
      }
    }
}
</script>

<style>

</style>